const Koa = require('koa');
const app = new Koa();
const json = require('koa-json');
const onerror = require('koa-onerror');
const bodyparser = require('koa-bodyparser');
const logger = require('koa-logger');
const {checkToken} = require('./src/utils/checkToken')
const router = require('koa-router')();
const index = require('./src/routes/index');


const log4js = require('./src/utils/log4j');
const {success,fail,getIp,CODE,getPlaceByIp} = require('./src/utils/util');

// error handler
onerror(app);

require('./src/utils/db');

// middlewares
app.use(
  bodyparser({
    enableTypes: ['json', 'form', 'text'],
  })
);
app.use(json());
app.use(logger());

const unNeedTokens = ['users/login','users/register']


// logger
app.use(async (ctx, next) => {
  const start = new Date();
  await next();
  const ms = new Date() - start;
  const rest = await getPlaceByIp(getIp(ctx.req))
  log4js.info(rest)
  log4js.info(`ip:${getIp(ctx.req)} place:${await getPlaceByIp(getIp(ctx.req))} ${ctx.method} ${ctx.url} - ${ms}ms ${JSON.stringify(ctx.request.query || ctx.request.body)}`);

});

app.use(async (ctx,next)=>{
  let wantPaths = ctx.req.url.split('/')
  const wantPath = wantPaths.slice(2,4).join('/')
  if(unNeedTokens.indexOf(wantPath) === -1 ){
    const token = ctx.req.headers.authorization ?? " "
    const decoded  = await checkToken(token)
    if(!decoded){
      ctx.status = 200;
      ctx.body = fail('Token认证失败', CODE.AUTH_ERROR)
    }else{
      await next()
    }
  }else{
    await next()
  }
})

// routes
router.prefix('/api');
router.use(index.routes(), index.allowedMethods());
app.use(router.routes(), router.allowedMethods());

// error-handling
app.on('error', (err, ctx) => {
  log4js.error(`error${new Date().getTime}:${err.stack}`);
});

module.exports = app;
